﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI.WebControls;

namespace Nasa8x.Core
{
    public class GenericComparer
    {
        public List<GenericComparer> Comparers { get; set; }
        int _level;

        public SortDirection SortDirection { get; set; }
        public PropertyInfo PropertyInfo { get; set; }

        public int Compare<T>(T t1, T t2)
        {
            int _ret;

            if (_level >= Comparers.Count)
                return 0;

            object _t1Value = Comparers[_level].PropertyInfo.GetValue(t1, null);
            object _t2Value = Comparers[_level].PropertyInfo.GetValue(t2, null);

            if (t1 == null || _t1Value == null)
            {
                if (t2 == null || _t2Value == null)
                {
                    _ret = 0;
                }
                else
                {
                    _ret = -1;
                }
            }
            else
            {
                if (t2 == null || _t2Value == null)
                {
                    _ret = 1;
                }
                else
                {
                    _ret = ((IComparable)_t1Value).CompareTo(((IComparable)_t2Value));
                }
            }
            if (_ret == 0)
            {
                _level += 1;
                _ret = Compare(t1, t2);
                _level -= 1;
            }
            else
            {
                if (Comparers[_level].SortDirection == SortDirection.Descending)
                {
                    _ret *= -1;
                }
            }
            return _ret;
        }
    }
}
